package com.lebang.service;

import com.lebang.domain.MemberSdkError;
import com.lebang.example.MemberSdkErrorExample;
import com.lebang.mapper.MemberSdkErrorMapper;
import com.lebang.mapper.SdkErrorLogMapper;
import com.lebang.model.MemberSdkErrorModel;
import com.lebang.model.cences.CencesMsg;
import com.lebang.service.mongodb.CencesMsgMongodb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class MemberSdkErrorService {

    @Autowired
    private MemberSdkErrorMapper memberSdkErrorMapper;
    @Autowired
    private SdkErrorLogMapper sdkErrorLogMapper;
    @Autowired
    private CencesMsgMongodb cencesMsgMongodb;

    /**
     * 用户错误码出现最大次数
     */
    public static Integer MEMBER_ERROR_CODE_COUNT = 30;

    public long countByExample(MemberSdkErrorExample example) {
        return memberSdkErrorMapper.countByExample(example);
    }


    public List<MemberSdkErrorModel> selectByExample(MemberSdkErrorExample example) {
        return memberSdkErrorMapper.selectByExa(example);
    }

    /**
     * 用户数据源错误码统计
     *
     * @param end
     */
    public void starDataInit(LocalDateTime end) {

        LocalDate now = end.toLocalDate().minusDays(1);

        long starTime = System.currentTimeMillis();
        //star 开始日期  end 结束日期
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));

        //结束日期
        LocalDateTime endDateTime = LocalDateTime.of(end.toLocalDate(), LocalTime.MIN);
        //开始日期
        LocalDateTime starDateTime = endDateTime.minusDays(1);
        //统计用户数据源错误码
        List<MemberSdkErrorModel> memberSdkErrorModels = sdkErrorLogMapper.cencusMemberSdkErrorByDateTime(starDateTime, endDateTime);
        for (MemberSdkErrorModel memberSdkErrorModel : memberSdkErrorModels) {
            if (memberSdkErrorModel.getNum() < MEMBER_ERROR_CODE_COUNT) {
                continue;
            }
            MemberSdkError memberSdkError = new MemberSdkError();
            memberSdkError.setCreateDate(now);
            memberSdkError.setMemberId(memberSdkErrorModel.getMemberId());
            memberSdkError.setErrorCode(memberSdkErrorModel.getErrorCode());
            memberSdkError.setSdkKey(memberSdkErrorModel.getSdkKey());
            memberSdkError.setNum(memberSdkErrorModel.getNum());
            memberSdkErrorMapper.insertSelective(memberSdkError);

        }
        cencesMsgMongodb.save(new CencesMsg("用户数据源错误码统计", (System.currentTimeMillis() - starTime)));

    }
}
